package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 自定义过滤器，编写过滤逻辑
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //编写过滤逻辑
        log.info("【AuthorizeFilter】:网关过滤器准备校验jwt");
        //1.获取request 和 response 对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        log.info("【AuthorizeFilter】:获取request:【{}】 和 response【{}】",request,response);
        //判断是否登录
        if(request.getURI().getPath().contains("/login")){
            //放行
            log.info("【AuthorizeFilter】:网关过滤器放行登录");
            return chain.filter(exchange);
        }
        try {
            //获取token
            List<String> headers = request.getHeaders().get("token");
            String token = headers.get(0);
            if(StringUtils.isEmpty(token)){
                //token不存在，返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //结束请求
                log.info("【AuthorizeFilter】:token不存在");
                return response.setComplete();
            }
            //检验token是否有效
            Claims claims = AppJwtUtil.getClaimsBody(token);
            //判断是否过期
            int result = AppJwtUtil.verifyToken(claims);
            if(result == 1 || result == 2){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                log.info("【AuthorizeFilter】:token过期");
                return response.setComplete();
            }

            //获取用户信息
            Object userId = claims.get("id");
            log.info("【获取用户id:{}】",userId);

            //存入header中
            ServerHttpRequest serverHttpRequest = request.mutate().header("userId", userId.toString()).build();
            log.info("【将用户id存入请求头中:{}】",serverHttpRequest);
            //重置请求
            exchange.mutate().request(serverHttpRequest);


        }catch (Exception e){
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            log.info("【AuthorizeFilter】:token解析过程出错");
            return response.setComplete();
        }
        //放行
        log.info("【AuthorizeFilter】:网关过滤器校验jwt成功");
        return chain.filter(exchange);

    }

    /**
     * 设置优先级
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
